package com.qianduo.front.service;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpHostConnectException;

import com.qianduo.front.exception.ServiceException;
import com.qianduo.front.model.Proxy;
import com.qianduo.front.util.Constants;

import common.httpclient.util.HttpClientUtil;
import common.util.StringUtil;

public class CommonService {
	protected String className					= this.getClass().getName();
	public static final String user_agent      	= "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2";
	public static final String accept          	= "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
	public static final String accept_language 	= "zh-cn,zh;q=0.5";
	public static final String encoding			= "utf-8";
	public static final int timeOut				= 5000;
	
	public void setPostOrGet(HttpRequest base,String host,String at,String referer,String cookie){
		base.setHeader("Host", host);
		base.setHeader("User-Agent", user_agent);
		if(StringUtil.isEmpty(at)){
			base.setHeader("Accept", accept);
		}else{
			base.setHeader("Accept", at);
		}
		base.setHeader("Accept_Language", accept_language);
		//base.setHeader("Accept_Encoding", accept_encoding);
		//base.setHeader("Accept_Charset", accept_charset);
		if(!StringUtil.isEmpty(referer)){
			base.setHeader("Referer",referer);
		}
		if(!StringUtil.isEmpty(cookie)){
			base.setHeader("Cookie",cookie);
		}
		base.setHeader("Origin","http://"+host);
	}
	public void setPostOrGet(HttpRequest base,String host,String at,String referer,String cookie,String origin){
		base.setHeader("Host", host);
		base.setHeader("User-Agent", user_agent);
		if(StringUtil.isEmpty(at)){
			base.setHeader("Accept", accept);
		}else{
			base.setHeader("Accept", at);
		}
		base.setHeader("Accept_Language", accept_language);
		if(!StringUtil.isEmpty(referer)){
			base.setHeader("Referer",referer);
		}
		if(!StringUtil.isEmpty(cookie)){
			base.setHeader("Cookie",cookie);
		}
		if(!StringUtil.isEmpty(origin)){
			base.setHeader("Origin",origin);
		}else{
			base.setHeader("Origin","http://"+host);
		}
	}	
	/*commonPost times*/
	@SuppressWarnings("finally")
	public HttpResponse commonPost(boolean isProxy,Proxy proxy,String query,List<NameValuePair> list,Map<String,String> map,String encoding,String host,String sessionID,int times) throws ServiceException{
		HttpResponse res	= null;	
		try{
			HttpPost post	= new HttpPost(query);
			HttpClient hc	= HttpClientUtil.getHttpClient(Constants.TIME_OUT);
			if(isProxy){
						hc	= HttpClientUtil.getHttpClient(Constants.TIME_OUT, proxy.getIp(), proxy.getPort());
			}
			HttpClientParams.setRedirecting(hc.getParams(), false);
			UrlEncodedFormEntity entity	= new UrlEncodedFormEntity(list, encoding);
			post.setEntity(entity);
			if(null != map && map.size() > 0){
				for(Entry<String,String> entry : map.entrySet()){
					post.setHeader(entry.getKey(),entry.getValue());
				}
			}
			setPostOrGet(post, host, null, null, sessionID);
			res	= hc.execute(post);
			/*
			if(query.indexOf("PeerPayOrder.aspx") != -1){
				throw new UnknownHostException("测试");
			}
			*/
		}catch(SocketTimeoutException e){
			Constants.log.info(query+" commonPost 读取超时!");
		}catch(UnknownHostException e){
			if(times < Constants.UNKNOWN_HOST_TRY_TIMES){
				Constants.log.info(query+" commonPost UnknownHostException 已重试 "+(times)+"次");
				return commonPost(isProxy, proxy, query, list, map, encoding, host, sessionID,++times);
			}else{
				Constants.log.info(query+" commonPost UnknownHostException 已重试 "+(times)+"次");
			}
		}catch(HttpHostConnectException e){
			Constants.log.info(query+" 服务器拒绝访问!");
		}catch(ConnectTimeoutException e){
			Constants.log.info(query+" 服务器连接超时!");
		}catch(Exception e){
			throw new ServiceException("Common commonPost", e);
		}finally{
			return res;
		}
	}
	/*commonPost*/
	public HttpResponse commonPost(boolean isProxy,Proxy proxy,String query,List<NameValuePair> list,Map<String,String> map,String encoding,String host,String sessionID) throws ServiceException{
		return commonPost(isProxy, proxy, query, list, map, encoding, host, sessionID,1);
	}
	
	/*commonGet times*/
	@SuppressWarnings("finally")
	public HttpResponse commonGet(boolean isProxy,Proxy proxy,String query,Map<String,String> map,String host,String sessionID,int times) throws ServiceException{		
		HttpResponse res	= null;	
		try{
			HttpGet get		= new HttpGet(query);			
			HttpClient hc	= HttpClientUtil.getHttpClient(Constants.TIME_OUT);
			if(isProxy){
						hc	= HttpClientUtil.getHttpClient(Constants.TIME_OUT, proxy.getIp(), proxy.getPort());
			}
			HttpClientParams.setRedirecting(hc.getParams(), false);
			if(null != map && map.size() > 0){
				for(Entry<String,String> entry : map.entrySet()){
					get.setHeader(entry.getKey(),entry.getValue());
				}
			}
			setPostOrGet(get, host, null, null, sessionID);
			res	= hc.execute(get);
			/*
			if(query.indexOf("PeerPayOrder.aspx") != -1){
				System.out.println(new Source(new InputStreamReader(res.getEntity().getContent(),"gbk")));
				throw new UnknownHostException("测试");
			}
			*/
		}catch(SocketTimeoutException e){
			Constants.log.info(query+" commonGet 读取超时!");
		}catch(UnknownHostException e){
			if(times < Constants.UNKNOWN_HOST_TRY_TIMES){
				Constants.log.info(query+" commonGet UnknownHostException 已重试 "+(times)+"次");
				return commonGet(isProxy, proxy, query, map, host, sessionID,++times);
			}else{
				Constants.log.info(query+" commonGet UnknownHostException 已重试 "+(times)+"次");
			}
		}catch(HttpHostConnectException e){
			Constants.log.info(query+" 服务器拒绝访问!");
		}catch(ConnectTimeoutException e){
			Constants.log.info(query+" 服务器连接超时!");
		}catch(Exception e){
			throw new ServiceException("Common commonGet", e);
		}finally{
			return res;
		}
	}
	/*commonGet*/
	public HttpResponse commonGet(boolean isProxy,Proxy proxy,String query,Map<String,String> map,String host,String sessionID) throws ServiceException{
		return commonGet(isProxy, proxy, query, map, host, sessionID,1);
	}
}
